<template>
  <div class="component-icon-btn" @click="handleOpen">
    <div class="component-icon-btn-icon">
      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><g fill="none" fill-rule="evenodd"><rect stroke="#3D4757" x="1.5" y="1.5" width="13" height="13" rx="1" /><path fill="#3D4757" d="M2 5h12v1H2z" /><path d="M14.7 11.814l-2.601-2.48a.5.5 0 00-.697.007l-2.367 2.34-1.698-1.62a.5.5 0 00-.724.036L5.3 11.626l.629.703 1.087-1.265L9.046 13l2.712-2.681 2.378 2.267.564-.772zM9 9a1 1 0 100-2 1 1 0 000 2z" fill="#3D4757" fill-rule="nonzero" /><path fill="#3D4757" d="M6 2v13H5V2z" /></g></svg>
    </div>
    <el-dialog
    title="上传图片"
    :visible.sync="dialogVisible"
    append-to-body
    :close-on-click-modal="false"
    :before-close="beforeClose"
    width="600px">
      <el-upload
        ref="uploadImageTemplateRef"
        action=""
        :multiple="false"
        accept=".jpg,.jpeg,.png,.gif"
        :on-change="changeFiles"
        :limit="1"
        :auto-upload="false"
        style="height: 80px;"
      >
        <el-button slot="trigger" size="small">选取文件</el-button>
        <el-button type="primary" style="margin-left: 10px;" size="small" @click="submitUpload">上传到服务器</el-button>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script>
import { uploadImageTemplate } from '@/api/designer'
export default {
  props: {
    context: {
      type: Object,
      required: true
    }
  },
  data: function() {
    return {
      form: {
        file: null
      },
      dialogVisible: false
    }
  },
  mounted: function() {

  },
  methods: {
    handleOpen() {
      this.form.file = null
      this.dialogVisible = true
    },
    beforeClose(done) {
      if(this.form.file) {
        this.$refs.uploadImageTemplateRef.clearFiles()
      }
      done()
    },
    changeFiles(file, fileList) {
      this.form.file = file
    },
    submitUpload() {
      if(this.form.file === null) {
        this.$message('请选择上传文件');
        return
      }
      const formData = new FormData()
      formData.append('file', this.form.file.raw)
      uploadImageTemplate(formData).then((response) => {
        this.$refs.uploadImageTemplateRef.clearFiles()
        this.dialogVisible = false
      })
    }
  }
}
</script>
